package com.gxa.clientorder.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.gxa.clientorder.pojo.Order;
import com.gxa.clientorder.service.OrderService;
import com.gxa.clientorder.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author FanJiang
 * @Date 2020/11/18
 * @Version 1.0
 */

@Controller
public class PayController {

    //APPID
    private final String APP_ID = "2016110200786295";

    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCx0s9dAke6sjs9Vo15OniAEiFAgI+1OzGfLo6iw59Bx5H5nfID7SCWAo+nDFjHH5TX3Ap951oAS3KbjjAQHr1l6qwGCIEPVj03hoMDr5vzCMG2Jvozh+wtEmnTSvITc0xia+C5iw5JmH+YGF6so19qME+fS1PrP+JD1dDe4Pn+kbrYFxzSiDSuCbSNEVbQyKd5jOYsR+6kqTwAdk4XSkWuvVKTAZur63jt/7wfo8XLX/d0hpUBv6MJsrOJbNEm9v/g3szkyIzYVXT6yKO6qtdTxiMeVdve5ON10NVkXWsiMDk2cL4cjvc6C58KXUTlWCySJj6by1wcB5XfG1NNAIGbAgMBAAECggEAaHaTYuxH/yFdM7d4/NKgn3wHFMFxquHPUNgk6vFIyXfYBXAIEM5o6jcu9M+IB9JBul2FvFkAwlOQTFnHWnD0ir7Ft/We+8eJxui6ZpvvXWKzibJ0IXmkAQZkLMBGXa7KHLeLGPTbu9hefJc0Zu7Cyrr+y3GRJw4sefVN8uDve+Bdhht9rTPwipTKMCV4yA8p/iRw22avD9BEzo/69lp8mdHrnA1l1QWzW62Pceme4jx2Jtwh2jEB5JhlSzQDKJvve5yumsNBhlfaPaAGX/aphM0bbD7KeoYYbJTRhP0aZpPB8w3qfCSYCrRfJ5A+wuUalRnM50PO3vfp/mYQdyD5AQKBgQDgcAJaxIp6FrfMtP8BVfPI/XI8m/IJ/q449aiQddU+S6OqGUDsfRtIVcJOiSvalzYRtIzcPWWmsSSovsB7RXzRZCuSwSWStc0Y7i7wDBztLFw2aW1RpSS5WwmtKTKLv9MaTGicksOPuqV/NVM0UdInHM/aFeZIzm0nloU8TmT6oQKBgQDK1KUag1P/zq/XsXRW03skdDBEH1OCdfM299WhSff5je6PkTtCW1cke9PsCQr/QlgsovFJH0us/sX9k1C341hZXXlBslG/KGbKLeKhyCknYn7okzio6QYRxtraE3CrEbuQi9Mctd9gsYF0QLWn3jW9k9eW6wNveKVbHjdbgGSuuwKBgBvkr9Y6EP/FbQhrAjpXRVoYbacstnMZjOuVVGLH0j3QxsFwLAp4Lfjad7CtCZ88JcMjjlIc61JBN84lDuUDKNUZPvUZPiMypw/PIlRBHSM43SkCB00bWioTL2uu8BJAP+tHzcSP1PA7ATCDHxkkhhrIUOjIyfsIdLZz1ZE+KPyhAoGATu0cKgr8fshQyJ/242p7up2zwm5mMpfvQm6CJLcB1YwTTq523sVoTXwZ5PlH3DhW01e8iHWzHugs5xWSDVxcHrou2w+mm7n+9aGRVN7slLTRKXNQUvoKMJSuyLlT2F2YHREr3zouaBPqifA8P8xKITEMbV+aAKBzx9ckN2joxM0CgYAjz3D/yDGnHmw4K1iHmbJid1vL6HX8eHhSEZzmYHz/JUDip8tQ88Eq7Be4gVBmLZohQOh4Mj4Q87TqRV8aVuq/JTmVsfJ5nrt3yArahwgdiqyr7Ne0ZnTz1w+GG+ZEzbz5BZqxHL1+4bbSTRTuJ5kcpV4aWBW3+k4PgxS2RJ+vqQ==";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgcgETHWFx4PpqTFkMFPP4DHCfHYvKTqlIppgqg1Dfc2jvUfn6byiIFGtydwjdtTvo7AiZOxZoK5gnx6MzqQg3j01k9OUIhLiXdKyJGetGX/NfAvfZzNYhuY/PySBqBSEgSkjvHc/uiYq6m3NopY+2kNWhR67oeeVBBEEbQ/Rf/brHcmHBSLPG0zHZM7zxoAsrvj/TpMmpknaoehGxuIAyiPbAJ6t2Be9lZTp51ZDQwGBpOmRFtlSZ52+5N2otuJTWFTizFE1XscewTk3dAnpQVcgSQ6O0CEXAudw+FSs7pzPJzLj5UaoMd9CfmMRuiseL0JV3j6SMVX23Ey06Xm8CQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://139.196.223.193/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8861/returnUrl";

    @Resource
    OrderService orderService;
    @Resource
    ProductService productService;

    @RequestMapping("alipay")
    public void alipay(HttpServletResponse httpResponse,String ordnum) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //根据订单编号,查询订单相关信息
        Order orderbynum = orderService.findByOrdnum(ordnum);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderbynum.getOrdnum();
        //付款金额，必填
        String total_amount = orderbynum.getMoney().toString();
        //利用订单中的商品编号查询到商品名称
        Map probysysnum = productService.findBysysnum(orderbynum.getSysnum());
        Map product = (Map) probysysnum.get("data");
        //订单名称，必填
        String subject = product.get("name").toString();
        //商品描述，可空
        String body = (String) product.get("description");
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public Boolean returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功修改订单状态
            orderService.updatePay(out_trade_no,1);
           return true;
        }

        return false;
    }

}

